<template>
  <!-- 设备管理 -->
  <div id="eqFaultEditDiv">
    <GoBack :content="titleType()" :backUrl="backUrl" :faultId="faultId" :pageSize="pageSize" :pageIndex="pageIndex"></GoBack>
    <el-container>
      <div class="padding-sm" style="width: 70%; padding-top: 10px">
        <el-scrollbar style="height: 100%">
          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">设备信息
                <vxe-button v-if="checkEquiptShow" @click="checkEquiptDialog" type="text" class="button-blue margin-left-xs" icon="vxe-icon-square-plus">选择设备</vxe-button>
              </div>
            </template>
            <el-descriptions-item label="设备编码">
              <vxe-input disabled v-model="faultForm.equiptCode"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="设备名称">
              <vxe-input v-model="faultForm.equiptName"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="设备型号">
              <vxe-input v-model="faultForm.specification"></vxe-input>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">故障信息</div>
            </template>
            <el-descriptions-item label="故障单号">
              <vxe-input disabled v-model="faultForm.faultNo" placeholder="自动生成"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="发生时间">
              <vxe-input v-model="faultForm.faultDate" placeholder="日期选择" type="datetime" transfer></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="操作人">
              <vxe-input v-model="faultForm.faultOptor"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="主修人">
              <vxe-select v-model="faultForm.personId" placeholder="请选择主修人" style="width: 58%;" filterable transfer @change='changeType'>
                <vxe-option v-for="typeObj in personList" :key="typeObj.id" :label="typeObj.name" :value="typeObj.id" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item label="故障类型">
              <el-select v-model="faultForm.faultType" placeholder="请选择故障类型" ref="selectOrgRef"  style="width:180px;">
                <el-option hidden :value="faultForm.faultType ? faultForm.faultType : ''" :label="faultForm.faultTypeName"></el-option>
                <el-tree filterable :data="faultTypeList" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" @node-click="handleTypeNodeClick" highlight-current ref="orgTreeRef" node-key="faultTypeCode" class="tools-tree"></el-tree>
              </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="故障等级">
              <vxe-select v-model="faultForm.faultGrade" placeholder="请选择保养类型" style="width: 58%;" transfer>
                <vxe-option v-for="typeObj in faultGradeList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item label="紧急程度">
              <vxe-select v-model="faultForm.urgency" placeholder="请选择紧急程度" style="width: 58%;" transfer>
                <vxe-option v-for="typeObj in urgencyList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item :span="2" />

            <el-descriptions-item :span="3" label="故障描述">
              <vxe-textarea v-model="faultForm.faultRemark"></vxe-textarea>
            </el-descriptions-item>
          </el-descriptions>

        </el-scrollbar>
        <div class="footer">
          <el-form :inline="true">
            <el-row>
              <el-col :offset="1">
                <el-form-item>
                  <vxe-button :disabled="!checkEquiptShow" type="text" class="button-blue" icon="vxe-icon-save" content="确认" :loading="sloading" @click="saveFaultRepair"></vxe-button>
                </el-form-item>
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="关闭" @click="closeFaultRepair"></vxe-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-container>
  </div>
  <vxe-modal v-model="isEqVisiable" width="45vw" show-footer :mask="false">
    <template #title>
      <span class="text-bold">选择设备</span>
    </template>
    <template #default>
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input style="width: 130px" v-model="searchEqForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findEquiptList" @keyup="keyupEqEnter" @search-click="findEquiptList"></vxe-input>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findEquiptList"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="equiptTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="equipmentList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column title="序号" width="80">
            <template #default="{ row, rowIndex, column }">
              <span>{{ rowIndex + 1 }}</span>
            </template>
          </vxe-column>
          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="equiptCode" title="编码"></vxe-column>
          <vxe-column field="equiptName" title="名称"></vxe-column>
          <vxe-column field="equiptTypeName" title="设备类型"></vxe-column>
          <vxe-column field="specification" title="型号"></vxe-column>
          <vxe-column field="activationDate" title="启用日期"></vxe-column>
        </vxe-table>
      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelEqEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="confirmEqEvent">确定</vxe-button>
    </template>
  </vxe-modal>

</template>
  <script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, notifyMessage, notifyType } from '@/utils/common';
import GoBack from '@/components/GoBackNew.vue'; //返回组件
let { proxy }: any = getCurrentInstance();

let backUrl = ref(null);
let pageSize = ref(null);
let pageIndex = ref(null);
let faultId = ref(null);
let isEqVisiable = ref(false);
let checkEquiptShow = ref(false);
let lloading = ref(false); //弹框表格数据加载状态
let ploading = ref(false); //弹框表格数据加载状态
let dloading = ref(false); //弹框表格数据加载状态
let sloading = ref(false);
let equipmentList: any = reactive([]); //弹框表格数据
let personList: any = reactive([]); //弹框表格数据
let faultTypeList: any = reactive([]); //选择字典
let faultGradeList: any = reactive([]);
let faultReasonList: any = reactive([]);
let repairStatusList: any = reactive([]);
let repairGradeList: any = reactive([]);
let repairTypeList: any = reactive([]);
let urgencyList: any = reactive([]);
let defaultProps = {
  children: 'children',
  label: 'faultTypeName'
};
let searchEqForm = reactive({
  searchValue: ''
});

let faultForm = reactive({
  id: null,
  faultNo: '',
  equiptId: '',
  equiptCode: '',
  equiptName: '',
  specification: '', //设备型号
  faultDate: '',
  faultOptor: '',
  faultPerson: '',
  personId: '',
  faultType: '',
  faultTypeName: '',
  faultGrade: '',
  faultRemark: '',
  faultStatus: '5',
  urgency: '',
  seq: 1
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['faultGrade', 'repairStatus', 'faultReason', 'repairGrade', 'repairType', 'repairUrgency'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const faultGrades = dictTreeTypeItems.data.find((item: any) => item.code === 'faultGrade');
  faultGradeList.push(...faultGrades.detailDataList);
  const repairStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'repairStatus');
  repairStatusList.push(...repairStatues.detailDataList.filter((a: any) => a.code != '0').filter((a: any) => a.code != '20'));
  const faultReasons = dictTreeTypeItems.data.find((item: any) => item.code === 'faultReason');
  faultReasonList.push(...faultReasons.detailDataList);
  const repairGrades = dictTreeTypeItems.data.find((item: any) => item.code === 'repairGrade');
  repairGradeList.push(...repairGrades.detailDataList);
  const repairTypes = dictTreeTypeItems.data.find((item: any) => item.code === 'repairType');
  repairTypeList.push(...repairTypes.detailDataList);
  const repairUrgencys = dictTreeTypeItems.data.find((item: any) => item.code === 'repairUrgency');
  urgencyList.push(...repairUrgencys.detailDataList);
}

onMounted(() => {
  findFaultTypeTree();
  getDictItemsList(); //批量获取字典
  findPersonList();
  if (!IsEmpty(proxy.$route.query.url)) {
    backUrl.value = proxy.$route.query.url.toString();
  }
  if (!IsEmpty(proxy.$route.query.pageSize)) {
    pageSize.value = proxy.$route.query.pageSize.toString();
  }
  if (!IsEmpty(proxy.$route.query.pageIndex)) {
    pageIndex.value = proxy.$route.query.pageIndex.toString();
  }

  if (!IsEmpty(proxy.$route.query.id)) {
    faultForm.id = proxy.$route.query.id.toString();
    faultId.value = proxy.$route.query.id.toString();
  }

  if (!IsEmpty(faultForm.id)) {
    findEqFaultRepairById();
  } else {
    checkEquiptShow.value = true;
  }
});

function findFaultTypeTree() {
  faultTypeList.length = 0;

  const url = '/api/eq/eqFaultType/findFaultTypeTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        faultTypeList.push(...res.data.faultTypeTree);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取机构失败', VxeNotifyType.error);
    });
}

function findEqFaultRepairById() {
  const url = '/api/eq/eqFaultRepair/findEqFaultRepairById';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        id: faultForm.id
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        if (!IsEmpty(res.data)) {
          Object.assign(faultForm, res.data);
          setCurOrgTreeNode(faultForm.faultType);

          if (faultForm.faultStatus == '0') {
            checkEquiptShow.value = true;
          }
        }
      } else {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 光标定位在指定字典分类上
function setCurOrgTreeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

function checkEquiptDialog() {
  findEquiptList();
  isEqVisiable.value = true;
}

/**关闭窗体 */
function cancelEqEvent() {
  isEqVisiable.value = false;
}

/**确认选择 */
async function confirmEqEvent() {
  const selectRows = (proxy.$refs.equiptTableRef as any).getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择设备', VxeNotifyType.error);
  } else if (selectRows.length > 1) {
    VxeMessage('只能选择一个设备', VxeNotifyType.error);
  } else {
    let sltEquipt = selectRows[0];
    faultForm.equiptId = sltEquipt.id;
    faultForm.equiptCode = sltEquipt.equiptCode;
    faultForm.equiptName = sltEquipt.equiptName;
    faultForm.specification = sltEquipt.specification;
    isEqVisiable.value = false;
  }
}

function findEquiptList() {
  lloading.value = true;
  equipmentList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqEquipment/findEqEquipmentList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchEqForm.searchValue
      }
    })
    .then((res: any) => {
      equipmentList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}
function findPersonList() {
  ploading.value = true;
  personList.length = 0; //放入数据前清空数据
  const url = '/api/sys/hisEmployee/getPubEmployeeList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      personList.push(...res.data);
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEqEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findEquiptList();
  }
}

function saveFaultRepair() {
  sloading.value = true;
  if (faultForm.id === null) {
    const url = '/api/eq/eqFaultRepair/addFaultRepair';
    const supplier = {
      faultNo: faultForm.faultNo,
      equiptId: faultForm.equiptId,
      equiptCode: faultForm.equiptCode,
      equiptName: faultForm.equiptName,
      specification: faultForm.specification,
      faultDate: faultForm.faultDate,
      faultOptor: faultForm.faultOptor,
      faultPerson: faultForm.faultPerson,
      personId: faultForm.personId,
      faultType: faultForm.faultType,
      faultGrade: faultForm.faultGrade,
      faultRemark: faultForm.faultRemark,
      faultStatus: faultForm.faultStatus,
      urgency: faultForm.urgency,
      seq: 1
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('新增成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { faultId: res.data.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
        } else {
          VxeMessage('新增失败', VxeNotifyType.error);
        }
        sloading.value = false;
        //findQiIndexSqlOne();
      })
      .catch((err: any) => {
        sloading.value = false;
        console.log(err);
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/api/eq/eqFaultRepair/updatFaultRepair';

    const supplier = {
      id: faultForm.id,

      faultNo: faultForm.faultNo,
      equiptId: faultForm.equiptId,
      equiptCode: faultForm.equiptCode,
      equiptName: faultForm.equiptName,
      specification: faultForm.specification,
      faultDate: faultForm.faultDate,
      faultOptor: faultForm.faultOptor,
      faultPerson: faultForm.faultPerson,
      personId: faultForm.personId,
      faultType: faultForm.faultType,
      faultGrade: faultForm.faultGrade,
      faultRemark: faultForm.faultRemark,
      faultStatus: faultForm.faultStatus,
      urgency: faultForm.urgency,
      seq: faultForm.seq
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('修改成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { faultId: faultForm.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
        } else {
          VxeMessage('修改失败', VxeNotifyType.error);
        }
        sloading.value = false;
      })
      .catch((err: any) => {
        sloading.value = false;
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

function closeFaultRepair() {
  proxy.$router.push({ path: backUrl.value, query: { faultId: faultForm.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
}
// 判断中间弹框显示的标题
function titleType() {
  if (faultForm.id) {
    return `维护报修`;
  } else if (!faultForm.id) {
    return `添加报修`;
  }
}
function changeType(row: any) {
  for (const item of personList) {
    if (item.id == row.value) {
      faultForm.faultPerson = item.name;
    }
  }
}

function handleTypeNodeClick(data: any) {
  faultForm.faultType = data.faultTypeCode;
  faultForm.faultTypeName = data.faultTypeName;
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}
</script>
  
  <style lang="scss" scoped>
#eqFaultEditDiv {
  .el-descriptions {
    margin-top: 10px;
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    box-shadow: 8px 8px 15px #909399;
    background-color: $bg-gray;
    z-index: 9999;
    .el-form {
      transform: translateX(5%);
    }
    .el-form-item {
      margin-bottom: 0;
      margin-right: 12px;
    }
  }
}
</style>